package com.jims.api.v1.controller.sync;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.my.controller.BaseController;
import com.jims.master.common.data.Message;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.*;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.base.netHosptial.entity.NetDataIcd10;
import com.jims.master.modules.base.netHosptial.service.NetDataIcd10Service;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterDoctorinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;
import com.jims.master.modules.base.user.service.MasterDoctorinfoService;
import com.jims.master.modules.sync.service.NetHisLoggerService;
import com.jims.master.modules.sync.entity.*;
import com.jims.master.modules.sync.service.*;
import com.jims.master.modules.sys.entity.OrgDict;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.OrgDictService;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.weChatSweepPay.pay.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 门诊摘要controller
 * @author ct
 * @version 2017-11-17
 */
@RestController
@RequestMapping(value = "/clinic")
public class ClinicMasterController extends BaseController {
    @Autowired
    private ClinicMasterService clinicMasterService;
    @Autowired
    private OrgDictService orgDictService;
    @Autowired
    private ExamItemService examItemService;
    @Autowired
    private ExamApplyService examApplyService;
    @Autowired
    private PrescriptionEnService prescriptionEnService;
    @Autowired
    private LabApplyService labApplyService;
    @Autowired
    private DiagnosisService diagnosisService;

    @Autowired
    private NetDataIcd10Service netDataIcd10Service;

    @Autowired
    private MasterDoctorinfoService masterDoctorinfoService;
    @Autowired
    private MasterBaseinfoService masterBaseinfoService;
    @Autowired
    private NetHisLoggerService netHisLoggerService;
    @Autowired
    private TransferRecordService transferRecordService;
    /**
      * @Title: clinicMaster
      * @Description: 查询门诊摘要信息
      * @param clinicId
      * @return
      * @author CT
      * @date 2017/11/17 0017
      * @throws
     */
    @RequestMapping(value = "V100/clinicMaster",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String clinicMasterV100(@RequestParam(required = true)String clinicId){
	/*	Map<String, Object> map = new HashMap<String, Object>();*/
		/*map.put("registList",registList);*/
        ClinicMaster clinicMaster = clinicMasterService.get(clinicId);
        Message mes = new Message();
        mes.setData(clinicMaster);
        return SecurityUtil.encryptMsgData(mes);
    }

    @RequestMapping(value = "V100/deleteclinicV100",method ={RequestMethod.GET,RequestMethod.POST})
    public String deleteclinicV100(@RequestParam(required = true)String id){
	/*	Map<String, Object> map = new HashMap<String, Object>();*/
		/*map.put("registList",registList);*/
        int i = clinicMasterService.deleteClinic(id);
        Message mes = new Message();

        mes.setData(i);
        return SecurityUtil.encryptMsgData(mes);
    }

    @RequestMapping(value = "V100/deleteDiagnosis",method ={RequestMethod.GET,RequestMethod.POST})
    public String deleteDiagnosisV100(@RequestParam(required = true)String id){
        int i = diagnosisService.deleteDiagnosis(id);
        Message mes = new Message();
        mes.setData(i);
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * @Title: clinicMasterV100
     * @Description: 通过医生和患者身id查询患者的开单记录
     * @param doctorId
     * @param patientId
     * @return
     * @author WangYQ
     * @date 2018/03/21
     * @throws
     */
    @RequestMapping(value = "V100/getByDocPatIdCard",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String getByDocPatIdCard(@RequestParam(required = true)String doctorId,@RequestParam(required = true)String patientId){
        Message msg = new Message();
        List<ClinicMaster> list = clinicMasterService.getByDocPatIdCard(doctorId,patientId);
        msg.setData(list);
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: mobileBillingV100
     * @Description: (医生端给患者开单)
     * @param doctorId
     * @param idCard
     * @param mobile
     * @param age
     * @param baseInfo
     * @param orgId
     * @param name
     * @return
     * @author WangYQ
     * @date 2018/03/21
     * @throws
     */
    @RequestMapping(value = "V100/mobileBilling",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String mobileBilling(@RequestParam(required = true)String doctorId,@RequestParam(required = true)String idCard,@RequestParam(required = true)String mobile,@RequestParam(required = true)String age,@RequestParam(required = true)String baseInfo,@RequestParam(required = true)String orgId,@RequestParam(required = true)String name){
        Message msg = new Message();
        ClinicMaster clinicMaster = clinicMasterService.mobileBilling( doctorId, idCard, mobile, age, baseInfo,orgId,name);
        if(StringUtils.isNotBlank(clinicMaster.getId())){
            msg.setData(clinicMaster);
        }else {
            msg.setData("开单保存失败");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: save
     * @Description: 门诊病历保存
     * @return
     * @author jict
     * @date 2018/03/21
     * @throws
     */
    @RequestMapping(value = "V100/save",method ={RequestMethod.GET,RequestMethod.POST})
    public String save(String  hisPresent,String chiefComplaint,String clinicId){
        Message msg = new Message();
        int i = clinicMasterService.updateClinin(hisPresent, chiefComplaint, clinicId);
        if (i>0) {
            msg.setData("保存成功");
        }else{
            msg.setData("保存失败");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: save
     * @Description: 门诊诊断icd10关键字模糊查询
     * @return
     * @author jict
     * @date 2018/03/21
     * @throws
     */
    @RequestMapping(value = "V100/selectIcd10",method ={RequestMethod.GET,RequestMethod.POST})
    public String save(String name){
        Message msg = new Message();
        List<NetDataIcd10> netDataIcd10List= netDataIcd10Service.hisDataIcdName(name);
        msg.setData(netDataIcd10List);
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: save
     * @Description: 门诊诊断保存
     * @return
     * @author jict
     * @date 2018/03/21
     * @throws
     */
    @RequestMapping(value = "V100/saveDiagnosis",method ={RequestMethod.GET,RequestMethod.POST})
    public String saveDiagnosis(String diagnosies){
        JSONArray jsonArray = JSONArray.parseArray(diagnosies);
        int result=0;
        for (int i=0;i<jsonArray.size();i++){
            JSONObject jsonJ = jsonArray.getJSONObject(i);
            String ss = jsonJ.toString();
            Diagnosis diagnosis = JSON.parseObject(ss,Diagnosis.class);
            diagnosis.setParentIds("0");
             int j= diagnosisService.save(diagnosis);
             result++;
        }
        Message msg = new Message();
        if (result>0) {
            msg.setData("保存成功");
        }else{
            msg.setData("保存失败");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: clinicMasterV100
     * @Description: 组织数据向his传输(根据问诊id查询本次问诊所有信息)
     * @param clinicId
     * @author jict
     * @date 2018/03/21
     * @throws
     */
    @RequestMapping(value = "V100/post",method ={RequestMethod.GET,RequestMethod.POST})
    public String post(@RequestParam(required = true)String clinicId,@RequestParam(required = true)String orgId){
        OrgDict orgdict = orgDictService.get(orgId);
        Message msg = new Message();
        PrescriptionEn prescriptionEn = new PrescriptionEn();
        ClinicMaster clinicMaster = clinicMasterService.getByClinic(clinicId);
        MasterBaseinfo masterBaseinfo = masterBaseinfoService.get(clinicMaster.getBaseInfo());
//      年龄为必填项，所以直接从基本信息表中获取数据
        if(StringUtils.isNotBlank(masterBaseinfo.getAge())){
            clinicMaster.setAge(masterBaseinfo.getAge());
        }else{
            msg.setStatus("0");
            msg.setData("患者基本信息缺失年龄");
            return SecurityUtil.encryptMsgData(msg);
        }
        if(StringUtils.isNotBlank(masterBaseinfo.getSex())){
            clinicMaster.setSex(masterBaseinfo.getSex());
        }else{
            msg.setStatus("0");
            msg.setData("患者基本信息缺失性别");
            return SecurityUtil.encryptMsgData(msg);
        }
        /*if(StringUtils.isNotBlank(clinicMaster.getAgeYear())){
            clinicMaster.setAge(clinicMaster.getAgeYear());
        }else{
            if(StringUtils.isNotBlank(clinicMaster.getAgeMonth())){
                clinicMaster.setAge(clinicMaster.getAgeMonth());
            }else {
                clinicMaster.setAge(getAgefromBirthTime(clinicMaster.getIdCard())+"");
            }
        }*/
//      防止医生信息不全，以便测试接口
        MasterDoctorinfo masterDoctorinfo = masterDoctorinfoService.get(clinicMaster.getDoctorId());
        if(masterDoctorinfo.getBaseinfo()==null){
            msg.setStatus("0");
            msg.setData("医生的基本信息不全");
            return SecurityUtil.encryptMsgData(msg);
        }
        String doctorCard=masterDoctorinfo.getBaseinfo().getIdCard();
        if(masterDoctorinfo.getBaseinfo().getIdCard()==null||masterDoctorinfo.getBaseinfo().getIdCard().equals("")){
            msg.setStatus("0");
            msg.setData("医生身份证信息不全");
            return SecurityUtil.encryptMsgData(msg);
        }
//        MasterBaseinfo masterBaseinfo =masterBaseinfoService.get(masterDoctorinfo.getBaseinfo().getId());
//        clinicMaster.setDoctorCard("132626195503260032");
        clinicMaster.setDoctorCard(doctorCard);
        clinicMaster.setOrgId(orgId);
        BaseDto baseDto = new BaseDto();
        List<BaseDto> params = new ArrayList<BaseDto>();
        List<BaseDto> list=null;
        baseDto.put("clinicMaster", clinicMaster);
        String kd="开单",zh="转诊";
        String yydz=orgdict.getLabel()+"(地址："+orgdict.getAddress()+")";
        String dydz="一楼健康体检处";
        String slqrmyy="一楼简易门诊处";

//      转诊
        if(clinicMaster.getHisType().equals("1")){
            TransferRecord transferRecord=transferRecordService.findByClinicId(clinicId);
            if(transferRecord!=null){
                baseDto.put("transferRecord", transferRecord);
                list = uploadHis(baseDto, orgId);
                if(list!=null&&list.size()>0){
                    BaseDto baseDto1=list.get(0);
                    if(baseDto1.get("warnCode").toString().equals("0")){
                        if(orgId.equals("861100341")){
                            String sd="尊敬的"+masterBaseinfo.getName()+"，"+masterDoctorinfo.getBaseinfo().getName()+"医生已给您"+zh+"到"+yydz+"，请凭门诊号"+clinicMaster.getClinicNo()+"和身份证到医院"+dydz+"就诊，欢迎您使用康需平台。";
                            SendSms.sendSmsO(masterBaseinfo.getMasterContactinfo().getMobilePhone(),sd);
                        }else {
                            String sd="尊敬的"+masterBaseinfo.getName()+"，"+masterDoctorinfo.getBaseinfo().getName()+"医生已给您"+zh+"到"+yydz+"，请凭门诊号"+clinicMaster.getClinicNo()+"和身份证到医院"+slqrmyy+"就诊，欢迎您使用康需平台。";
                            SendSms.sendSmsO(masterBaseinfo.getMasterContactinfo().getMobilePhone(),sd);
                        }
                       netHisLoggerService.save(clinicMaster,baseDto1);
                    }
                    msg.setStatus("0");
                    msg.setData(baseDto1);
                }else {
                    msg.setData("开单失败");
                }
            }else {
                msg.setData("转诊记录为空");
            }

            return SecurityUtil.encryptMsgData(msg);
        }else if(clinicMaster.getHisType().equals("0")){
            List<ExamApply> examApply = examApplyService.getByClinicId(clinicId);
            List<LabApply> labApply = labApplyService.getByClinicId(clinicId);
            prescriptionEn.setClinicId(clinicId);
            List<PrescriptionEn> prescriptionEnList= prescriptionEnService.getByBillingId(prescriptionEn);
//      判断是否有数据，有数据传送，没数据不传送
            int i=0;
//          判断现病史、主诉、诊断是否有值
            if(clinicMaster.getHisPresent()!=null&&!clinicMaster.getHisPresent().equals("")){
                i+=1;
            }
            if (clinicMaster.getChiefComplaint()!=null&&!clinicMaster.getChiefComplaint().equals("")){
                i+=1;
            }
            if (clinicMaster.getDiagnosisList()!=null&&clinicMaster.getDiagnosisList().size()>0){
                i+=1;
            }
//          判断检查、检验、处方
            if(examApply!=null&&examApply.size()>0){
                baseDto.put("examApplyJson", examApply);
                i+=1;
            }
            if(labApply!=null&&labApply.size()>0){
//              给his传耗材  类型  数量
                for(int lab=0;lab<labApply.size();lab++){
                    LabApply la=labApply.get(lab);
                    if(labApply.get(lab).getLabConsumabl()!=null){
                        LabConsumabl labConsumabl=labApply.get(lab).getLabConsumabl();
                        la.setBloodNum(Integer.parseInt(labConsumabl.getNum()));
                        la.setBloodType(labConsumabl.getType());
                    }
                }
                baseDto.put("labApplyJson", labApply);
                i+=1;
            }
            if(prescriptionEnList!=null&&prescriptionEnList.size()>0){
                baseDto.put("prescriptionJson", prescriptionEnList);
                i+=1;
            }
            if(i>0){
                list = uploadHis(baseDto,orgId);
                if(list!=null&&list.size()>0){
                    BaseDto baseDto1=list.get(0);
                    if(baseDto1.get("warnCode").toString().equals("0")){
                        if(orgId.equals("861100341")){
                            String sd="尊敬的"+masterBaseinfo.getName()+"，"+masterDoctorinfo.getBaseinfo().getName()+"医生已给您"+kd+"到"+yydz+"，请凭门诊号"+clinicMaster.getClinicNo()+"和身份证到医院"+dydz+"就诊，欢迎您使用康需平台。";
                            SendSms.sendSmsO(masterBaseinfo.getMasterContactinfo().getMobilePhone(),sd);
                        }else {
                            String sd="尊敬的"+masterBaseinfo.getName()+"，"+masterDoctorinfo.getBaseinfo().getName()+"医生已给您"+kd+"到"+yydz+"，请凭门诊号"+clinicMaster.getClinicNo()+"和身份证到医院"+slqrmyy+"就诊，欢迎您使用康需平台。";
                            SendSms.sendSmsO(masterBaseinfo.getMasterContactinfo().getMobilePhone(),sd);
                        }

                        netHisLoggerService.save(clinicMaster,baseDto1);
                    }
                    msg.setStatus("0");
                    msg.setData(baseDto1);
                }else {
                    msg.setData("开单失败");
                }
            }else {
                msg.setData("开单信息不全");
            }
            return SecurityUtil.encryptMsgData(msg);
        }else {
            msg.setData("门诊主记录信息不全无法进行转诊、开单操作");
            return SecurityUtil.encryptMsgData(msg);
        }

    }

    /**
     * @Title: saveTransferRecord
     * @Description: 保存转诊信息
     * @param map
     * @author ct
     * @date 2018/04/11
     * @throws
     */
    @RequestMapping(value = "V100/saveTransferRecord", method = {RequestMethod.GET, RequestMethod.POST})
    public String saveTransferRecord(@RequestParam(required = true) Map map) {
        Message msa = new Message();
        int i = clinicMasterService.saveTransferRecord(map);
        msa.setData(i);
        return SecurityUtil.encryptMsgData(msa);
    }

    /**
     * @Title: getBaseByDoctor
     * @Description: 根据医生查询转诊患者列表
     * @param doctorId
     * @author ct
     * @date 2018/04/13
     * @throws
     */
    @RequestMapping(value = "V100/getBaseByDoctor", method = {RequestMethod.GET, RequestMethod.POST})
    public String getBaseByDoctor(@RequestParam(required = true) String doctorId) {
        Message msa = new Message();
        List<TransferRecord> baseList = transferRecordService.getBaseByDoctor(doctorId);
        msa.setData(baseList);
        return SecurityUtil.encryptMsgData(msa);
    }

    /**
     * @Title: getBaseByBaseinfo
     * @Description: 根据用户id得到转诊列表
     * @param userId
     * @author ct
     * @date 2018/04/17
     * @throws
     */
    @RequestMapping(value = "V100/getBaseByBaseinfo", method = {RequestMethod.GET, RequestMethod.POST})
    public String getBaseByBaseinfo(@RequestParam(required = true) String userId) {
        Message msa = new Message();
        List<TransferRecord> baseinfoList = transferRecordService.getBaseByBaseinfo(userId);
        msa.setData(baseinfoList);
        return SecurityUtil.encryptMsgData(msa);
    }

    /**
     * @Title: getBaseByBaseinfo
     * @Description: 根据转诊id得到转诊详情
     * @param id
     * @author ct
     * @date 2018/04/17
     * @throws
     */
    @RequestMapping(value = "V100/getBaseById", method = {RequestMethod.GET, RequestMethod.POST})
    public String getBaseById(@RequestParam(required = true) String id) {
        Message msa = new Message();
        TransferRecord transferRecord = transferRecordService.get(id);
        msa.setData(transferRecord);
        return SecurityUtil.encryptMsgData(msa);
    }

    @RequestMapping(value = "V100/getBaseByClinic", method = {RequestMethod.GET, RequestMethod.POST})
    public String getBaseByClinic(@RequestParam(required = true) String id) {
        Message msa = new Message();
        TransferRecord transferRecord = transferRecordService.getByClinic(id);
        msa.setData(transferRecord);
        return SecurityUtil.encryptMsgData(msa);
    }


    public List<BaseDto> uploadHis(BaseDto baseDto,String orgId){
        List<BaseDto> list=null;
        List<BaseDto> params = new ArrayList<BaseDto>();
        params.add(baseDto);
        list = WebServiceUtils.getExamList(orgId, "/doctorJob/V100/saveHealthOfDoctotrJob", params);
        return list;
    }

    /**
     * @Title: getCountByDoctor
     * @Description: 统计医生转诊和开单人数
     * @param doctorId
     * @author jicunteng
     * @date 2018/04/24
     * @throws
     */
    @RequestMapping(value = "V100/getCountByDoctor", method = {RequestMethod.GET, RequestMethod.POST})
    public String getCountByDoctor(@RequestParam(required = true) String doctorId) {
        Message msa = new Message();
        List<ClinicMaster> zhuan = clinicMasterService.getZhuanZheng(doctorId);
        List<ClinicMaster> kai = clinicMasterService.getKaiDan(doctorId);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("zhuanZheng",zhuan);
        map.put("kaiDan",kai);
        msa.setData(map);
        return SecurityUtil.encryptMsgData(msa);
    }

    @RequestMapping(value = "V100/labApplyList", method = {RequestMethod.GET, RequestMethod.POST})
    public String labApplyList(String url){
        Message msg=new Message();
        String s = HttpUtil.postData(url,"");
        msg.setData(s);
        return SecurityUtil.encryptMsgData(msg);
    }
    /**
     * @Title: idCardUtil
     * @Description: 通过省份证获取年龄
     * @param idCard
     * @author WangYQ
     * @date 2018/04/24
     * @throws
     */
    public  static  int  getAgefromBirthTime(String idCard){
        String birthTimeString = idCard.substring(6,10)+"-"+idCard.substring(10,12)+"-"+idCard.substring(12,14);
        // 先截取到字符串中的年、月、日
        String strs[] = birthTimeString.trim().split("-");
        int selectYear = Integer.parseInt(strs[0]);
        int selectMonth = Integer.parseInt(strs[1]);
        int selectDay = Integer.parseInt(strs[2]);
        // 得到当前时间的年、月、日
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);

        // 用当前年月日减去生日年月日
        int yearMinus = yearNow - selectYear -1;
        int monthMinus = monthNow - selectMonth;
        int dayMinus = dayNow - selectDay;

        int age = yearMinus;
        if (yearMinus < 0) {// 选了未来的年份
            age = 0;
        } else if (yearMinus == 0) {// 同年的，要么为1，要么为0
            if (monthMinus < 0) {// 选了未来的月份
                age = 0;
            } else if (monthMinus == 0) {// 同月份的
                if (dayMinus < 0) {// 选了未来的日期
                    age = 0;
                } else if (dayMinus >= 0) {
                    age = 1;
                }
            } else if (monthMinus > 0) {
                age = 1;
            }
        } else if (yearMinus > 0) {
            if (monthMinus < 0) {// 当前月>生日月
            } else if (monthMinus == 0) {// 同月份的，再根据日期计算年龄
                if (dayMinus < 0) {
                } else if (dayMinus >= 0) {
                    age = age + 1;
                }
            } else if (monthMinus > 0) {
                age = age + 1;
            }
        }
        return age;

    }
    /**
     * @Title: getNoUploadedBilling
     * @Description: 获取一段时间内未上传的开单列表
     * @param map
     * @author WangYQ
     * @date 2018/08/03
     * @throws
     */
    @RequestMapping(value = "V100/getNoUploadedBilling", method = {RequestMethod.GET, RequestMethod.POST})
    public String getNoUploadedBilling(@RequestParam(required = true) Map map){
        Message msa = new Message();
        List<ClinicMaster> list=clinicMasterService.getNoUploadedBilling(map);
        msa.setData(list);
        return SecurityUtil.encryptMsgData(msa);
    }

    /**
     * @Title: getNoUploadedBilling
     * @Description: 获取一段时间内未上传的开单列表
     * @param map
     * @author WangYQ
     * @date 2018/08/03
     * @throws
     */
    @RequestMapping(value = "V100/getUploadedBilling", method = {RequestMethod.GET, RequestMethod.POST})
    public String getUploadedBilling(@RequestParam(required = true) Map map,HttpServletRequest request, HttpServletResponse response){
        Message msa = new Message();
        Page<ClinicMaster> page = new Page<ClinicMaster>();
        page = clinicMasterService.getUploadedBilling(new Page<ClinicMaster>(request, response), map);
        List<ClinicMaster> list=page.getList();
        msa.setData(list);
        return SecurityUtil.encryptMsgData(msa);
    }

    /**
     * @Title: ordersList
     * @Description: 收费单列表
     * @param
     * @author WangYQ
     * @date 2018/10/09
     * @throws
     */
    @RequestMapping(value = "V100/ordersList", method = {RequestMethod.GET, RequestMethod.POST})
    public String ordersList(String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, "utf-8");
        url = url.replace("&amp;", "&");
        String s = HttpUtil.postData(url,"");
        return s;
    }
    /**
     * @Title: ordersList
     * @Description: 收费单明细
     * @param
     * @author WangYQ
     * @date 2018/10/09
     * @throws
     */
    @RequestMapping(value = "V100/ordersDetail", method = {RequestMethod.GET, RequestMethod.POST})
    public String ordersDetail(String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, "utf-8");
        url = url.replace("&amp;", "&");
        String s = HttpUtil.postData(url,"");
        return s;
    }
}
